<?php

namespace app\uniapp\service;

use app\common\exception\MiException;
use app\model\store\Goods;
use app\model\store\GoodsCart;
use app\model\store\GoodsCate;
use app\model\store\GoodsSku;
use app\uniapp\service\traits\InstanceTrait;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\model\Relation;

class GoodsService extends UniBaseService
{

    use InstanceTrait;

    private array|int $whereCate = [];
    private array|int $whereTag = [];

    private int $whereSkuId = 0;

    function initialize()
    {
        $this->model = new Goods();
    }

    function formatData(array $data): array
    {
        return $data;
    }


    /**
     * 这里传入cateId或id数组
     * @param array|int $cate_id
     * @return $this
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function setWhereCate(array|int $cate_id): static
    {
        if ($cate_id != 0){ // 分类id为0，不添加查询条件
            // 组装分类条件
            $cateSer =  GoodsCateService::instance();
            $cates = $cateSer->getAllCates();
            $cateIds = [];
            if (is_array($cate_id)){
                foreach($cate_id as $v){
                    $_cateIds = $cateSer->childrenIds($cates, $v);
                    $cateIds = array_merge($_cateIds, $cateIds);
                    // 追加当前分类
                    $cateIds[] = $v;
                }
            }else{
                $_cateIds = $cateSer->childrenIds($cates, $cate_id);
                $cateIds = array_merge($_cateIds, $cateIds);
                // 追加当前分类
                $cateIds[] = $cate_id;
            }
            $this->whereCate = $cateIds;
        }
        return $this;

    }

    public function setWhereTag(array|int $tagId): static
    {
        if ($tagId !=0){
            if (is_array($tagId)){

            }else{
                $tagId = [$tagId];
            }
            $this->whereTag = $tagId;
        }
        return $this;
    }


    /**
     * 产品查询的基础查询条件信息
     *
     * uniapp端的所有产品查询都需要通过这个函数调用
     *
     * 这次传入的条件是组装产品信息的特殊条件，必须按照函数内的指定格式传入
     * 忘了就自己看源码
     * @return Query
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function query(): Query
    {
        $cateIds = $this->whereCate;
        $tagIds = $this->whereTag;
//        $tagId = $where['tagId']??'';

        $query = Goods::alias('g')
            ->with(['replies' => function ($query) {
                $query->order('create_time', 'desc')->withLimit(5)->filter(function ($v) {
                    $v->createTimeStr = substr($v->create_time, 0, 10);
                    $v->imageArr = miExplode($v->images);
                });
            }, 'specs' => ['values']])
            ->where('g.site_id', $this->siteId)
            ->where('g.show_type', 1)
            ->where($this->where);


        if (count($cateIds) > 0){
            $query->field("g.*, gcr.cate_id")->leftJoin('goods_cate_rel gcr', 'g.id=gcr.goods_id')
                ->where('gcr.cate_id', 'in', $cateIds);
        }
        if (count($tagIds) > 0){
            $query->field("g.*, gtr.tag_id")->leftJoin('goods_tag_rel gtr', 'g.id=gtr.goods_id')
                ->where('gtr.tag_id', 'in', $tagIds);
        }


        $query->group('g.id')->filter(function ($v) {
            $v->imageArr = miExplode($v['images']);
            $v->image = $v['imageArr'][0];
            $v->showPrice = round($v->price??0,2);
            $v->showLinePrice = round($v->line_price??0,2);
            // 查询出运费模板
            $v->postageTpl = PostageTemplateService::instance()->setWhere(['id' => $v->postage_tpl_id])->find();

            // 商品在购物车中的数量
            if ($this->userId){
                $v->num = GoodsCart::where('user_id', $this->userId)->where('goods_id', $v->id)->value("num", 0);
            }else{
                $v->num = 0;
            }
            $domain = request()->domain();
            $v->content = preg_replace('/(<img.+?src=")(\/uploads)/','$1'.$domain.'$2', $v->content);

            // 添加该商品下可使用的优惠券
//            CouponService::instance()->setWhere()

        });
        return $query;
    }


    /***
     * 根据id获取商品详情,并获取选中的SKU的信息
     * @param int $id
     * @param int $skuId
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    function getDetailById(int $id, int $skuId=0): mixed
    {
        $info = $this->query()->find($id);
        if ($info){
            $info->skus = $this->getSkusByGoodsId($info->id);
            $info->sku = null;
            if ($skuId){
                foreach ($info->skus as $sku){
                    if ($sku->id == $skuId){
                        $info->sku = $sku;
                        break;
                    }
                }
            }
        }

        return $info;
    }

    /** 根据产品id获取产品的所有规格信息
     * @param int $goodsId
     * @return Collection|array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    function getSkusByGoodsId(int $goodsId): Collection|array
    {
        return GoodsSku::with('specRels')->where('goods_id', $goodsId)->withoutField(['create_time', 'update_time'])->filter(function ($v) {
            $v->showPrice = round($v->price ?? 0, 2);
            $v->showLinePrice = round($v->line_price ?? 0, 2);
            $v->specValueIdArr = miExplode($v->spec_value_ids);
            $arr = [];
            foreach ($v->specRels as $spec) {
                $arr[] = $spec->spec_value;
            }
            $v->specValueStr = miImplode($arr, ' ');    // 规格字符串
            // 商品在购物车中的数量
            if ($this->userId){
                $v->num = GoodsCart::where('user_id', $this->userId)->where('goods_sku_id', $v->id)->count();
            }else{
                $v->num = 0;
            }

        })
            ->select();
    }


}
